<template>
  <div class="main">
    <breadcrumb/>
    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <el-row>
        <el-col>
          选择商品分类：
          <el-cascader
            v-model="selectedOptionValue"
            :options="cateOptions"
            @change="handlerCascaderChange"
            :props="cateOptionProps"
            clearable
            expand-trigger="hover"
          >
          </el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleTabsClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button :disabled="isThreeLevelCate" type="primary" size="mini" @click="paramsDialogVisible = true">添加参数
          </el-button>
          <el-table :data="manyTableData" stripe border>
            <el-table-column label="#" type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="i"
                  v-for="(item,i) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleTagClose(scope.row,item)"
                >
                  {{item}}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  class="el-icon-edit"
                  size="mini"
                  @click="modifyParamsDialogOpen(scope.row.attr_id)"
                >编辑
                </el-button>
                <el-button
                  type="danger"
                  class="el-icon-delete"
                  size="mini"
                  @click="deleteParams(scope.row.attr_id)"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button :disabled="isThreeLevelCate" type="primary" size="mini" @click="paramsDialogVisible = true">添加属性
          </el-button>
          <el-table :data="onlyTableData" stripe border>
            <el-table-column label="#" type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="i"
                  v-for="(item,i) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleTagClose(scope.row,item)"
                >
                  {{item}}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  class="el-icon-edit"
                  size="mini"
                  @click="modifyParamsDialogOpen(scope.row.attr_id)"
                >编辑
                </el-button>
                <el-button
                  type="danger"
                  class="el-icon-delete"
                  size="mini"
                  @click="deleteParams(scope.row.attr_id)"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!--添加参数弹窗-->
    <el-dialog
      :title="'添加' + dialogText"
      :visible.sync="paramsDialogVisible"
      width="50%"
      @close="handlerAddParamsDialogClosed"
      :close-on-click-modal="false"
    >
      <el-form :model="paramsForm" label-width="100px" ref="paramsFormRef">
        <el-form-item
          :label="activeName === 'many' ? '动态参数' : '静态属性'"
          prop="attr_name"
          :rules="[{required: true, message: activeName === 'many' ? '请输入参数名称' : '请输入属性名称', trigger: 'blur'}]"
        >
          <el-input
            v-model="paramsForm.attr_name"
            :placeholder="activeName === 'many' ? '输入参数名称' : '输入属性名称'"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="paramsDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addParams">确 定</el-button>
  </span>
    </el-dialog>

    <!--修改参数弹窗-->
    <el-dialog
      :title="'修改' + dialogText"
      :visible.sync="modifyParamsDialogVisible"
      width="50%"
      @close="handlerModifyParamsDialogClosed"
      :close-on-click-modal="false"
    >
      <el-form :model="modifyParamsForm" label-width="100px" ref="modifyParamsFormRef">
        <el-form-item
          :label="activeName === 'many' ? '动态参数' : '静态属性'"
          prop="attr_name"
          :rules="[{required: true, message: activeName === 'many' ? '请输入参数名称' : '请输入属性名称', trigger: 'blur'}]"
        >
          <el-input
            v-model="modifyParamsForm.attr_name"
            :placeholder="activeName === 'many' ? '输入参数名称' : '输入属性名称'"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="modifyParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="modifyParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Breadcrumb from '@/components/Breadcrumb'
import { getCateList } from '../../../api/goods/cate'
import { addParams, deleteParams, getParams, getParamsData, modifyParams } from '@/api/goods/params'

export default {
  name: 'Params',
  components: { Breadcrumb },
  data: () => {
    return {
      selectedOptionValue: [],
      cateOptions: [],
      cateOptionProps: {
        value: 'cat_id',
        label: 'cat_name'
      },
      currentSelectedCateId: 0,
      activeName: 'many',
      manyTableData: [],
      onlyTableData: [],
      paramsDialogVisible: false,
      paramsForm: {
        attr_name: ''
      },
      modifyParamsDialogVisible: false,
      modifyParamsForm: {
        attr_name: ''
      }
    }
  },
  created () {
    this.getOptions()
  },

  computed: {
    isThreeLevelCate () {
      return this.selectedOptionValue.length !== 3
    },

    dialogText () {
      return this.activeName === 'many' ? '动态参数' : '静态属性'
    }
  },

  methods: {
    // 关闭tag标签
    async handleTagClose (row, tag) {
      const r = await this.$confirm('确定要删除该属性？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (r !== 'confirm') {
        return this.$message.info('已取消删除！')
      }
      row.attr_vals.splice(row.attr_vals.indexOf(tag), 1)
      const { data: res } = await modifyParams(this.currentSelectedCateId, row.attr_id, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
        return
      }
      this.$message.success(res.meta.msg)
    },

    // 点击添加标签按钮
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    // 当文本框失去焦点 或 按下回车按钮
    async handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      const { data: res } = await modifyParams(this.currentSelectedCateId, row.attr_id, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) {
        row.attr_vals.pop()
        this.$message.error(res.meta.msg)
        return
      }
      row.inputVisible = false
      row.inputValue = ''
      this.$message.success(res.meta.msg)
    },

    // 删除参数
    async deleteParams (attrId) {
      const message = this.activeName === 'many' ? '确定要删除该参数？' : '确定要删除该属性？'
      const r = await this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (r !== 'confirm') {
        return this.$message.info('已取消删除！')
      }
      const { data: res } = await deleteParams(this.currentSelectedCateId, attrId)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      await this.getParamsData()
    },

    // 修改参数信息
    modifyParams () {
      this.$refs.modifyParamsFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await modifyParams(this.currentSelectedCateId, this.modifyParamsForm.attr_id, {
          attr_name: this.modifyParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        await this.getParamsData()
        this.modifyParamsDialogVisible = false
      })
    },

    // 修改参数弹窗打开
    async modifyParamsDialogOpen (attrId) {
      const { data: res } = await getParams(this.currentSelectedCateId, attrId, this.activeName)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.modifyParamsForm = res.data
      this.modifyParamsDialogVisible = true
    },

    // 修改参数弹窗关闭
    handlerModifyParamsDialogClosed () {
      this.$refs.modifyParamsFormRef.resetFields()
    },

    // 添加参数弹窗关闭
    handlerAddParamsDialogClosed () {
      this.$refs.paramsFormRef.resetFields()
    },

    // 添加动态参数或静态属性
    addParams () {
      this.$refs.paramsFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await addParams(this.currentSelectedCateId, {
          attr_name: this.paramsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        await this.getParamsData()
        this.paramsDialogVisible = false
      })
    },

    // 标签页切换
    handleTabsClick () {
      this.getParamsData()
    },

    // 获取参数列表数据
    async getParamsData () {
      const { data: res } = await getParamsData(this.currentSelectedCateId, this.activeName)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      res.data.map(p => {
        p.attr_vals = p.attr_vals ? p.attr_vals.split(' ') : []
        p.inputVisible = false
        p.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      }
      this.onlyTableData = res.data
    },

    // 获取级联选择框数据
    async getOptions () {
      const { data: res } = await getCateList()
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateOptions = res.data
    },

    // 处理级联选择框发生改变
    handlerCascaderChange () {
      if (this.selectedOptionValue.length !== 3) {
        this.selectedOptionValue = []
        return
      }
      this.currentSelectedCateId = this.selectedOptionValue[2]
      this.getParamsData()
    }
  }
}
</script>
<style lang="less" scoped>
  @import "./index";
</style>
